<template>
    <div>
        <el-row>
            <el-col :span="24">
                <el-card style="margin: 20px">
                    <div slot="header" class="clearfix" style="text-align: center">
                        <el-progress type="circle" :percentage="percentage" :status="status"></el-progress>
                        <p v-if="noSelected">请选择导出目录后开始</p>
                    </div>
                    <div style="text-align: center">
                        <el-button plain="" @click="selectExportPath" style="font-weight: lighter">选择导出位置</el-button>
                        <div style="margin-top: 5px">
                            <p style="color: gray" @click="showItemInFolder(selectedPath)">{{selectedPath}}</p>
                        </div>
                    </div>
                    <div style="text-align: center">
                        <h4 style="color: rebeccapurple;font-weight: lighter">已生成文件列表</h4>
                    </div>
                    <div class="file-list" ref="fileList" style="border: 1px solid #ebeef5">
                        <ul>
                            <li v-for="file in fileLists" draggable="true"
                                @dragstart="fileDrag($event,file.path)">
                                <img v-if="path.extname(file.path || '') == '.docx'" src="~@/assets/Docs.png" style="width: 50px;height: 50px" alt="" draggable="false">
                                <img v-if="path.extname(file.path || '') == '.xlsx'"src="~@/assets/Sheets.png" style="width: 50px;height: 50px" alt="" draggable="false">
                                <p>{{file.name}}</p>
                                <el-button icon="el-icon-more" @click="showItemInFolder(file.path)" circle style="margin-left: 10px" size="mini"></el-button>
                                <el-button icon="el-icon-view" @click="openItem(file.path)" circle style="margin-left: 5px" size="mini"></el-button>
                            </li>
                        </ul>
                    </div>

                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    const os = require('os')
    const path = require('path')
    const fs = require('fs')
    const moment = require('moment')
    const {ipcRenderer} = require('electron')

    var JSZip = require('jszip')
    var Docxtemplater = require('docxtemplater')

    var XlsxTemplate = require('xlsx-template')

    export default {
      name: 'MultiResult',
      mounted () {
        document.title = '多人有限公司注册生成'
        console.log('mounted')
        console.log(this.$route.params)
        this.data = this.$route.params
        ipcRenderer.on('selected-directory', (event, path) => {
          this.selectedPath = path[0]
          this.noSelected = false
          // 开始处理文件生成
          this.fileLists = [] // 初始化成功文件列表
          // 生成日期文件夹名称
          var subTimeDir = moment().format('YYYY年MM月DD日HH点mm分ss秒')
          var companyName = this.data.mz_01 || '匿名公司'
          var subPath = companyName + subTimeDir
          let that = this
          this.docxPaths.forEach((path) => {
            that.genDocx(path, subPath)
          })
          this.xlsxPaths.forEach((path) => {
            that.genXlsx(path, subPath)
          })
          // 获取目标文件长度，并计算上边处理结果长度
          var desiredDocxLength = this.docxPaths.length || 0
          var desiredXlsxLength = this.xlsxPaths.length || 0
          var resFileLength = this.fileLists.length || 0
          var count = desiredDocxLength + desiredXlsxLength
          if (count > 0 && count === resFileLength) {
            this.percentage = 100
            this.status = 'success'
          } else {
            this.status = 'exception'
          }
        })
      },
      data () {
        return {
          path: path,
          data: null, // 数据
          percentage: 0, // 生成进度条 百分数
          status: null, // 生成状态
          noSelected: true, // 未选择目录
          selectedPath: os.homedir(), // 文件生成存放路径 用户选定 默认为用户目录下
          docxPaths: [
            path.resolve(__static, 'docx/两人有限公司/二人有限公司章程.docx'),
            path.resolve(__static, 'docx/两人有限公司/企税表.docx'),
            path.resolve(__static, 'docx/两人有限公司/无偿使用证明.docx'),
            path.resolve(__static, 'docx/两人有限公司/申请书.docx')
          ],
          xlsxPaths: [
            path.resolve(__static, 'docx/两人有限公司/公司注册登记表.xlsx')
          ],
          fileLists: [
          ]
        }
      },
      methods: {
        selectExportPath () {
          ipcRenderer.send('open-dir-dialog')
        },
        fileDrag (event, filePath) {
          console.log('文件拖拽开始')
          event.preventDefault()
          ipcRenderer.send('ondragstart', filePath)
        },
        showItemInFolder (fullPath) {
          this.$electron.shell.showItemInFolder(fullPath)
        },
        openItem (fullPath) {
          this.$electron.shell.openItem(fullPath)
        },
        genDocx (filePath, subPath) {
          // Load the docx file as a binary
          var content = fs
            .readFileSync(filePath, 'binary')

          var zip = new JSZip(content)

          var doc = new Docxtemplater()
          doc.loadZip(zip)
          // set the templateVariables
          doc.setData(this.data)
          try {
            // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
            doc.render()
          } catch (error) {
            var e = {
              message: error.message,
              name: error.name,
              stack: error.stack,
              properties: error.properties
            }
            console.log(JSON.stringify({error: e}))
            // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
            throw error
          }

          var buf = doc.getZip()
            .generate({type: 'nodebuffer'})

          // buf is a nodejs buffer, you can either write it to a file or do anything else with it.
          var targetPath = path.resolve(this.selectedPath, subPath)
          //   检测目录是否存在
          if (!fs.existsSync(targetPath)) {
            fs.mkdirSync(targetPath)
          }
          var savePath = path.resolve(targetPath, path.basename(filePath))
          fs.writeFileSync(savePath, buf)
          this.fileLists.push({
            name: path.basename(filePath),
            path: savePath
          })
          var desiredDocxLength = this.docxPaths.length || 0
          var desiredXlsxLength = this.xlsxPaths.length || 0
          var count = desiredDocxLength + desiredXlsxLength
          if (count > 0) {
            this.percentage += 100 / count
          }
        },
        genXlsx (filePath, subPath) {
          var content = fs.readFileSync(filePath)
          // Create a template
          var template = new XlsxTemplate(content)
          // Replacements take place on first sheet
          var sheetNumber = 1
          // Perform substitution
          template.substitute(sheetNumber, this.data)

          // Get binary data
          var newData = template.generate()
          var targetPath = path.resolve(this.selectedPath, subPath)
          //   检测目录是否存在
          if (!fs.existsSync(targetPath)) {
            fs.mkdirSync(targetPath)
          }
          var savePath = path.resolve(targetPath, path.basename(filePath))
          fs.writeFileSync(savePath, newData, 'binary')
          this.fileLists.push({
            name: path.basename(filePath),
            path: savePath
          })
          var desiredDocxLength = this.docxPaths.length || 0
          var desiredXlsxLength = this.xlsxPaths.length || 0
          var count = desiredDocxLength + desiredXlsxLength
          if (count > 0) {
            this.percentage += 100 / count
          }
        }
      }
    }
</script>

<style scoped>
    .file-list{
        padding: 10px;
    }
    .file-list ul {
        list-style: none;
        -webkit-padding-start: unset;
    }
    .file-list ul li{
        margin: 10px;
        padding: 10px;
        display: flex;
        height: 60px;
        border: 1px solid #ebeef5;
        align-items:center;
    }
</style>